import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import type { UserState } from './type/type'
import type { loginFormData, loginResponseData, userInfoReponseData } from '@/api/user/type'
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes'

import { cloneDeep } from 'lodash'
import router from '@/router'
//过滤用户异步路由函数
function filterAsyncRouter(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRouter(item.children, routes)
      }
      return true
    }
  })
}
export const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      username: '',
      avatar: '',
      buttons: [],
      menuRoutes: constantRoute,
    }
  },
  getters: {},
  actions: {
    //登录
    async userLogin(data: loginFormData) {
      const res: loginResponseData = await reqLogin(data)
      if (res.code === 200) {
        this.token = res.data
        SET_TOKEN(res.data)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    },

    //用户信息
    async userInfo() {
      const res: userInfoReponseData = await reqUserInfo()
      if (res.code === 200) {
        this.username = res.data.name
        this.avatar = res.data.avatar
        this.buttons = res.data.buttons
        //过滤出用户有权访问的异步路由
        const userAsyncRoute = filterAsyncRouter(cloneDeep(asyncRoute), res.data.routes)
        //整理出侧边菜单所需路由列表
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute]
        //将异步路由动态添加到路由
        ;[...userAsyncRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },

    //退出登录
    async userLogout() {
      //退出登录请求
      const result: any = await reqLogout()
      if (result.code == 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
})
